﻿using BW.Mes.WinForms.APi;
using BW.Mes.WinForms.Dto;
using BW.Mes.WinForms.WareHouse.Dto;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.WareHouse.SuppliedMaterialsForm;

namespace BW.Mes.WinForms.WareHouse.Libraryrecord
{
    public partial class GetLibraryrecordForm : DevExpress.XtraEditors.XtraForm
    {
        private ApiPaing<ShowLibraryrecord> showLibraryrecord;

        public GetLibraryrecordForm()
        {
            InitializeComponent();

            // 注册分页控件事件
            userControl11.ClickPageButtonEvent += UserControl1_ClickPageButtonEvent;
            userControl11.ChangedPageSizeEvent += UserControl1_ChangedPageSizeEvent;
            userControl11.JumpPageEvent += UserControl1_JumpPageEvent;
            this.Load += LibraryrecordForm_Load;
            //产品物料
            LoadMaterial();
            //仓库信息
            LoadStoragelocation();

        }

        private async void LibraryrecordForm_Load(object sender, EventArgs e)
        {
            await GetLibraryrecord();
            DisplayPagedData();
        }

        /// <summary>
        /// 获取来料标签打印记录
        /// </summary>
        public async Task GetLibraryrecord()
        {
            string queryParms = "?";
            if (textEdit1.Text != "")
            {
                queryParms += $"Receiptstype={textEdit1.Text}&";
            }
            if (gridLookUpEdit1.EditValue != null)
            {
                queryParms += $"Product={gridLookUpEdit1.EditValue}&";
            }
            if(gridLookUpEdit2.EditValue != null)
            {
                queryParms += $"StorageLocationId={gridLookUpEdit2.EditValue}&";
            }
            if(dateEdit1.EditValue != null && dateEdit2.EditValue != null)
            {
                queryParms += $"BeginTime={dateEdit1.EditValue}&EndTime={dateEdit2.EditValue}&";
            }





            var result = await HttpClientHepler.RequsetUrl(RequestType.get, MethodGolab.SHOW_LIBRAYRECORD+queryParms);
            
            //反序列化
            showLibraryrecord = JsonConvert.DeserializeObject<ApiPaing<ShowLibraryrecord>>(result);
            if (showLibraryrecord.code == 200)
            {
                this.gridControl1.DataSource = showLibraryrecord.pageDatas;
            }

            //// 设置总记录数和总页数
            userControl11.TotalRows = showLibraryrecord.totalCount;
            userControl11.TotalPages = (int)Math.Ceiling((double)showLibraryrecord.totalCount / userControl11.PageSize);

            // 更新页码信息标签
            userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{userControl11.TotalPages}页";


            // 确保清除旧数据源并重新设置
            gridControl1.DataSource = null;
            gridControl1.DataSource = showLibraryrecord;

            // 确保网格视图显示数据
            gridView1.PopulateColumns();
            gridView1.BestFitColumns();
            gridView1.RefreshData();

        }

        // 显示分页后的数据
        private void DisplayPagedData()
        {
            if (showLibraryrecord == null || showLibraryrecord.totalCount == 0)
                return;

            int startIndex = (userControl11.CurrentPage - 1) * userControl11.PageSize;
            int count = Math.Min(userControl11.PageSize, showLibraryrecord.totalCount - startIndex);

            if (startIndex < 0 || count <= 0)
                return;

            // 获取当前页的数据
            var pagedData = showLibraryrecord.pageDatas.Skip(startIndex).Take(count).ToList();

            // 绑定到GridControl
            gridControl1.DataSource = null;
            gridControl1.DataSource = pagedData;

            // 刷新网格视图
            gridView1.BestFitColumns();
            gridView1.RefreshData();
        }

        // 页码按钮点击事件处理
        private void UserControl1_ClickPageButtonEvent(int currentPage)
        {
            DisplayPagedData();
        }

        // 每页显示条数改变事件处理
        private void UserControl1_ChangedPageSizeEvent()
        {
            // 重新计算总页数
            userControl11.TotalPages = (int)Math.Ceiling((double)showLibraryrecord.totalCount / userControl11.PageSize);
            userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{userControl11.TotalPages}页";
            DisplayPagedData();
        }
         
        // 跳转页面事件处理
        private void UserControl1_JumpPageEvent(int jumpPage)
        {
            DisplayPagedData();
        }



        /// <summary>
        /// 加载物料信息
        /// </summary>
        private async void LoadMaterial()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T2/Product/GetProduct?PageIndex=1&PageSize=100");

                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    var jsonObject = JsonConvert.DeserializeObject<dynamic>(responseBody);

                    if (jsonObject["pageDatas"] != null)
                    {
                        // 将pageDatas转换为WareHouseItem列表
                        var dataJson = jsonObject["pageDatas"].ToString();
                        var warehouses = JsonConvert.DeserializeObject<List<Material>>(dataJson);

                        // 假设您改用了gridLookUpEdit1控件
                        gridLookUpEdit1.Properties.DataSource = warehouses;
                        gridLookUpEdit1.Properties.DisplayMember = "productName";
                        gridLookUpEdit1.Properties.ValueMember = "Id";

                        // 配置下拉框，只显示供应商名称
                        gridLookUpEdit1.Properties.View.Columns.Clear();
                        gridLookUpEdit1.Properties.View.Columns.Add(
                            new DevExpress.XtraGrid.Columns.GridColumn
                            {
                                FieldName = "productName",
                                Caption = "物料名称",
                                Visible = true
                            }
                        );

                        // 设置默认提示文本
                        gridLookUpEdit1.Properties.NullText = "请选择物料";
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载物料数据失败: {ex.Message}", "错误");
            }
        }


        /// <summary>
        /// 物料
        /// </summary>
        public class Material
        {
            public long Id { get; set; }
            public string productName { get; set; }
        }



        /// <summary>
        /// 加载库位信息
        /// </summary>
        private async void LoadStoragelocation()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T3/Storagelocation/GetStoragelocation?PageIndex=1&PageSize=100");

                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    var jsonObject = JsonConvert.DeserializeObject<dynamic>(responseBody);

                    if (jsonObject["pageDatas"] != null)
                    {
                        // 将pageDatas转换为WareHouseItem列表
                        var dataJson = jsonObject["pageDatas"].ToString();
                        var warehouses = JsonConvert.DeserializeObject<List<Storage>>(dataJson);

                        // 假设您改用了gridLookUpEdit1控件
                        gridLookUpEdit2.Properties.DataSource = warehouses;
                        gridLookUpEdit2.Properties.DisplayMember = "storageLocationName";
                        gridLookUpEdit2.Properties.ValueMember = "Id";

                        // 配置下拉框，只显示供应商名称
                        gridLookUpEdit2.Properties.View.Columns.Clear();
                        gridLookUpEdit2.Properties.View.Columns.Add(
                            new DevExpress.XtraGrid.Columns.GridColumn
                            {
                                FieldName = "storageLocationName",
                                Caption = "库位名称",
                                Visible = true
                            }
                        );

                        // 设置默认提示文本
                        gridLookUpEdit2.Properties.NullText = "请选择库位";
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载库位数据失败: {ex.Message}", "错误");
            }
        }


        /// <summary>
        /// 库位
        /// </summary>
        public class Storage
        {
            public long Id { get; set; }
            public string storageLocationName { get; set; }
        }

        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            await GetLibraryrecord();
            DisplayPagedData();
        }
        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void simpleButton3_Click(object sender, EventArgs e)
        {
            textEdit1.Text = "";
            gridLookUpEdit1.EditValue = "";
            gridLookUpEdit2.EditValue = "";
            dateEdit1.EditValue = "";
            dateEdit2.EditValue = "";
        }



        private void CreateLibraryrecord_Click(object sender, EventArgs e)
        {
            CreateLibraryrecordForm createLibraryrecordForm = new CreateLibraryrecordForm();
            createLibraryrecordForm.Show();
        }


        /// <summary>
        /// 添加货架/库区的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            var createForm = new CreateLibraryrecordForm();
            createForm.LibraryrecordAdded += CreateForm_LibraryrecordAdded;
            createForm.ShowDialog();
        }

        /// <summary>
        /// 自动刷新事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateForm_LibraryrecordAdded(object sender, EventArgs e)
        {
            // 刷新父窗体数据
            GetLibraryrecord(); // 假设这是加载数据的方法
        }





    }
}